package com.punai.web.controller.system;

import com.punai.common.annotation.Log;
import com.punai.common.constant.UserConstants;
import com.punai.common.core.controller.BaseController;
import com.punai.common.core.domain.AjaxResult;
import com.punai.common.core.domain.entity.SysCompany;
import com.punai.common.core.domain.entity.SysDept;
import com.punai.common.enums.BusinessType;
import com.punai.common.utils.SecurityUtils;
import com.punai.common.utils.StringUtils;
import com.punai.system.service.ISysCompanyService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/system/company")
public class SysCompanyController extends BaseController {

    @Autowired
    private ISysCompanyService sysCompanyService;


    /**
     * 获取公司列表
     */
    @PreAuthorize("@ss.hasPermi('system:company:list')")
    @GetMapping("/list")
    public AjaxResult list(SysCompany company)
    {
        List<SysCompany> companies = sysCompanyService.selectCompanyList(company);
        return AjaxResult.success(companies);
    }

    /**
     * 获取公司列表
     */
    @GetMapping("/treelist")
    public AjaxResult treelist()
    {
        SysCompany companies = sysCompanyService.treeCompanyList();
        List<SysCompany> arrayList = new ArrayList<>();
        arrayList.add(companies);
        return AjaxResult.success(arrayList);
    }

    /**
     * 查询公司列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:company:list')")
    @GetMapping("/list/exclude/{companyId}")
    public AjaxResult excludeChild(@PathVariable(value = "companyId", required = false) Long id)
    {
        List<SysCompany> depts = sysCompanyService.selectCompanyList(new SysCompany());
        depts.removeIf(d -> d.getId().equals(id) || ArrayUtils.contains(StringUtils.split(d.getPids(), ","), id + ""));
        return AjaxResult.success(depts);
    }

    /**
     * 根据公司编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:company:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        sysCompanyService.checkCompanyDataScope(id);
        return AjaxResult.success(sysCompanyService.selectCompanyById(id));
    }

    /**
     * 新增公司
     */
    @PreAuthorize("@ss.hasPermi('system:company:add')")
    @Log(title = "公司管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysCompany company)
    {
        if (UserConstants.NOT_UNIQUE.equals(sysCompanyService.checkCompanyNameUnique(company)))
        {
            return AjaxResult.error("新增公司'" + company.getCompanyName() + "'失败，公司名称已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(sysCompanyService.checkCompanyPrxUnique(company)))
        {
            return AjaxResult.error("新增公司'" + company.getPrx() + "'失败，公司简称已存在");
        }
        return toAjax(sysCompanyService.insertCompany(company));
    }

    /**
     * 修改公司
     */
    @PreAuthorize("@ss.hasPermi('system:company:edit')")
    @Log(title = "公司管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysCompany company)
    {
        Long id = company.getId();
        sysCompanyService.checkCompanyDataScope(id);
        if (UserConstants.NOT_UNIQUE.equals(sysCompanyService.checkCompanyNameUnique(company)))
        {
            return AjaxResult.error("修改公司'" + company.getCompanyName() + "'失败，公司名称已存在");
        }
        else if (company.getPid().equals(id))
        {
            return AjaxResult.error("修改公司'" + company.getCompanyName() + "'失败，上级公司不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, company.getStatus()) && sysCompanyService.selectNormalChildrenCompanyById(id) > 0)
        {
            return AjaxResult.error("该公司包含未停用的子公司！");
        }
        return toAjax(sysCompanyService.updateCompany(company));
    }

    /**
     * 删除公司
     */
    @PreAuthorize("@ss.hasPermi('system:company:remove')")
    @Log(title = "公司管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        if (sysCompanyService.hasChildByCompanyId(id))
        {
            return AjaxResult.error("存在下级子公司,不允许删除");
        }
        if (sysCompanyService.checkCompanyExistUser(id))
        {
            return AjaxResult.error("公司存在用户,不允许删除");
        }
        sysCompanyService.checkCompanyDataScope(id);
        return toAjax(sysCompanyService.deleteCompanyById(id));
    }


    /**
     * 根据当前公司前缀
     */
    @GetMapping(value = "/getCurrentPrx")
    public AjaxResult getCurrentPrx()
    {
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (admin) {
            return AjaxResult.success("manager");
        }
        Long companyId = SecurityUtils.getCompanyId();
        SysCompany sysCompany = sysCompanyService.selectCompanyById(companyId);
        return AjaxResult.success("操作成功",sysCompany.getPrx());
    }

    /**
     * 根据当前公司编号
     */
    @GetMapping(value = "/getCurrentId")
    public AjaxResult getCurrentId()
    {
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (admin) {
            return AjaxResult.success(1L);
        }
        Long companyId = SecurityUtils.getCompanyId();
        return AjaxResult.success("操作成功",companyId);
    }

}
